var itemno = "";
var applyid = "";
var nodeno = "";
var orgcode = "";
var nextnodecode1 = "";
var selectID = "userlist";
var instanceid;
$(function(){
	var applyno = getUrlParam("applyno");
	instanceid = getUrlParam("instanceid");
	$('#jointlysignopinion').hide();
	bindApplyForm(applyno);
	bindingJointlySignOpinion();
})


function bindApplyForm(applyno){

	$.ajax({ 
		url: basePath() + 'business/getapplyinfo.do',
		data: {"applyno": applyno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		for(var d in data.datas){//遍历json对象的每个key/value对,p为key
	    			if(d == 'applytime' || d == 'syscreated'){
	    				$('#' + d).html(formatDate(data.datas[d], 'yyyy-mm-dd hh:mi'));
	    			}
	    			else if(d == 'nodename'){
	    				if(data.datas[d] == '办结')
		    				$('#' + d).css('color', 'green');
	    				else if(data.datas[d].indexOf('补正')>0 || data.datas[d].indexOf('不予')>0)
		    				$('#' + d).css('color', 'red');
	    				else
		    				$('#' + d).css('color', 'blue');
	    				
	    				$('#' + d).html(data.datas[d]);
	    				$('#' + d).css('font-weight', 'bold');
	    			}
	    			else{
	    				$('#' + d).html(data.datas[d] == '' ? '/' : data.datas[d]);
	    			}
	    		}
	    		
	    		orgcode = data.datas.orgcode;

	    		applyid = data.datas.applyid;
	    		nodeno = data.datas.nodeno;

	    		$("#downallmaterial").attr("href","/gahCMP/business/downAllmaterial.do?applyid="+applyid);
	    		//绑定审批意见
	    		bindAuditOpinion(applyid,instanceid);
	    		
	    		
	    		//绑定业务资料
	    		itemno = data.datas.itemno;
	    		bindBusinessForm(applyid);

	    		$('#ifBusiness').load('../approval/business/detail/'+ itemno +'.html');

//	    		//绑定船舶数据
//	    		bindShipForm(applyid);
	    		
	    		//绑定附件材料
	    		bindMaterialListForm(applyid);	    

	    		//查询文书
	    		getBookByApplyid(applyid);
	    		
	    		//绑定下一节点
	    		bindNextNode(nodeno);
	    	}
      	}
	});
}

//function bindShipForm(applyid){
//	
//	$.ajax({ 
//		url: basePath() + 'business/getshipinfo.do',
//		data: {"applyid": applyid},
//		dataType: "json",
//        contentType: "application/json",
//		success: function(data){
//	    	if(data.result == 1){
//	    		for(var i=0; i< data.datas.length; i++){
//	    			bindShipData(data.datas[i]);
//	    		}
//	    	}
//      	}
//	});
//}
//function bindShipData(jsonShip){
//	for(var d in jsonShip){
//		$('#' + d).html(jsonShip[d]);
//	} 
//}

function bindBusinessForm(applyid){
	
	$.ajax({ 
		url: basePath() + 'business/getbusinessinfo.do',
		data: {"applyid": applyid, "itemno": itemno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		for(var d in data.datas){//遍历json对象的每个key/value对,p为key
	    			if (d == 'workbegintime' || d == 'workendtime'
									|| d == 'executionbegintime'
									|| d == 'executionendtime' || d == 'delaydate'
									|| d == 'worktime' || d == 'workstarttime' || d == 'rescuetime'
									|| d == 'ensurebegintime' || d == 'ensureendtime' || d == 'eventtime' || d == 'builddate') {
	    				$('#' + d).html(formatDate(data.datas[d], 'yyyy-mm-dd'));
	    			}
	    			else if(d == 'waterwayname' || d == 'navigationmarkname' ){
	    				$('#' + d).html(data.datas[d] == '' ? '' : data.datas[d] + ',');
	    			}
	    			else{
	    				if(itemno == '10003' && (d == "mobilephone" || d == "contactaddr")){
	    					$('#b' + d).html(data.datas[d] == '' ? '/' : data.datas[d]);
	    				}
	    				else
	    				$('#' + d).html(data.datas[d] == '' ? '/' : data.datas[d]);
	    			}
	    		}
	    		if(itemno=="10001" || itemno=="10002" || itemno=="10003"){
	    			bindCertificate(data.datas["recordcertificatelist"]);
	    		}
	    	}
      	}
	});
}

function bindCertificate(recordcertificatelist){
	for(var i=0;i<recordcertificatelist.length;i++){
		var html='	<tr>'+
		  '		<td>'+
		  recordcertificatelist[i]["certificatetypename"]+
		  '		</td>'+
		  '		<td>'+
		  formatDate(recordcertificatelist[i]["issuedate"])	+
		  '		</td>'+
		  '		<td>'+
		  formatDate(recordcertificatelist[i]["effectivedate"])	+
		  '		</td>'+
		  '		<td id="filename'+ recordcertificatelist[i]["certificateid"]+'"></td>'+
		  '	</tr>';	
		$("#recordcertificate").find('tbody').append(html);
		
		for(var j=0;j<recordcertificatelist[i]["recordcertificatefile"].length;j++){
			var filestr='<span style="display:block;">'+recordcertificatelist[i]["recordcertificatefile"][j]["FILEURL"]+'</span>'
			$("#filename"+recordcertificatelist[i]["certificateid"]).append(filestr);
		}
	}
}

function bindMaterialListForm(applyid){
	$.ajax({ 
		url: basePath() + 'business/getmaterialinfo.do',
		data: {"applyid": applyid},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		bindMaterial(data.datas);
	    	}
      	}
	});
}

function getBookByApplyid(applyid){
	$.ajax({ 
		url: basePath() + 'business/getamanuensis.do',
		data: {"applyid": applyid},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
	    		var bookData = data.datas;
	    		
	    		for(var i = 0; i < bookData.length; i++){
	    			var ahtml = '<a target="_blank" href="'+ bookData[i].fileurl +'"><button type="button" class="btn btn-link">'+ bookData[i].amanuensisname +'</button></a>'; 
	    			
	    			$('#book').append(ahtml);
	    		}
	    	}
      	}
	});
}

function bindNextNode(nodeno){
	$.ajax({ 
		url: basePath() + 'flow/getnextnodes.do',
		data: {"nodecode": nodeno},
		dataType: "json",
        contentType: "application/json",
		success: function(data){
			if(data.result == 1){
				var datas = data.datas;
				for(var i = 0; i < datas.length; i++){
					var nextnodecode = datas[i].nextnodecode;
					var nextnodename = datas[i].nextnodename;

					var controlhtml = '<input type="radio" value="'+ nextnodecode +'" text="'+ nextnodename +'"  name="nextnode" />';
					$("#nextnode").append(
							" <li>"
								+ controlhtml
								+ nextnodename
							+ "</li>");
				}
					    		

	    	    $("input[type=radio][name=nextnode]").bind("change", function() {

//					$('#opinion').val($(this).attr('text'));
		    		
					// 先清空控件数据
					$('#' + selectID).empty(); 
					
					var nextnodecode = $(this).attr('value');
					nextnodecode1 = nextnodecode;

					$.ajax({ 
						url: basePath() + 'flow/getuserbynodecode.do',
						data: {"nodecode": nextnodecode, "itemno": itemno, "orgcode": orgcode},
						dataType: "json",
				        contentType: "application/json",
						success: function(data){
					    	if(data.result == 1){

								for (var i = 0; i < data.datas.length; i++) {
									var value = data.datas[i].userid;
									var text = data.datas[i].username;
									
									var option = $("<option>").val(value).text(text).attr('data', JSON.stringify(data.datas[i])); 
									$('#' + selectID).append(option); 
								}
								
								var options = $('#' + selectID).find("option");
								options.first().attr("selected", true);
					    	}
				      	}
					});
				});
			}
      	}
	});
}

var tableID = 'material';
function bindMaterial(materialList){
	
    	
	for(var i = 0; i < materialList.length; i++){
		var ismustsubmit = materialList[i]['ismustsubmit'];
		var ismustsubmitStr = "";
		var must = false;
		if(ismustsubmit == 1){
			ismustsubmitStr = '<span style="color:red;">*</span>';
			must = true;
		}
		var index = materialList[i]['serialnumber'];
		var quantity = materialList[i]['quantity'];
		var materialname = materialList[i]['materialname'];
		var fileid="";
		var fileurl = materialList[i]['fileurl'];
		
		var trStr = '<tr>																													'+
					'	<td><span name="serialnumber">'+ index +'</span></td>																'+
					'	<td style="text-align: left;"><span name="materialname">'+ materialname + '</span>' + ismustsubmitStr +'</td>		'+
					'	<td>'+ quantity +'</td>																								'+
					'	<td id="filename_'+ index +'">																						'+
					'		'+ fileurl +'																									'+
					'	</td>																												'+
					'</tr>';
		
		$('#' + tableID).find('tbody').append(trStr);
	}
}

function save(){
	var users = []
	$('#' + selectID).find("option:selected").each(function(){
		users.push(jQuery.parseJSON($(this).attr('data')));
	})

	var businessid = applyid;
	var nodecode = nodeno;
	var opinion = $('#opinion').val();
	
	var formdata = {};
	formdata['businessid'] = businessid;
	formdata['nodecode'] = nodecode;
	formdata['opinion'] = opinion;
	formdata['nextnodecode'] = nextnodecode1;
	
	var params = {};
	params['auditopinion'] = formdata;
	params['users'] = users;
	
	if(!check(formdata, users))
		return true;
	
	
	$.ajax({ 
		method: 'post',
		url: basePath() + 'flow/auditopinion.do',
		data: JSON.stringify(params),
		dataType: "json",
        contentType: "application/json",
		success: function(data){
	    	if(data.result == 1){
				window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.success,{
					onOk:function(v){
			    		parent.refreshData();		//刷新数据
					}
				});	
	    	} 
	    	else{
	    		window.wxc.xcConfirm(data.info, window.wxc.xcConfirm.typeEnum.error);
	    	}
      	}
	});
}


function check(formdata, users){	
	var result = true;
	var strMsg = "";
	
	if(formdata['nextnodecode'] == '')	
		strMsg += '请选择下一步<br />';

	if(formdata['opinion'] == '')	
		strMsg += '请输入意见<br />';
	
//	if(users.length == 0)
//		strMsg += '请选择用户<br />';
	
	
	if(strMsg != ""){
    	window.wxc.xcConfirm(strMsg, window.wxc.xcConfirm.typeEnum.warning);
    	result = false;
	}
	
	return result;
}
function bindingJointlySignOpinion(){
	$.ajax({ 
		url: basePath() + 'flow/selectjointlysignnode.do',
		data: JSON.stringify({"instanceid":instanceid}),
		dataType: "json",
		type:"POST",
        contentType: "application/json",
		success: function(data){
			if(data.result == 1){
				for(i=0;i<data.datas.length;i++){
					$.ajax({ 
						url: basePath() + 'business/selectJointlySignOpinion.do',
						data: JSON.stringify({"instanceid": instanceid,"nodecode":data.datas[i].NODECODE}),
						dataType: "json",
						type:"POST",
						async:false,
				        contentType: "application/json",
						success: function(opiniondata){
							if(opiniondata.result==1){
								$('#jointlysignopinion').show();
								var html= '<div class="panel panel-primary" style="margin-top:10px">'+
								'<div class="panel-heading">'+
								'<h3 class="panel-title">'+
								data.datas[i].NODENAME+
								'会签信息'+
								'</div><div class="panel-body"><table class="table table-bordered" style="text-align: center;"><tr><th style="text-align: center;background-color: #eee;">用户名称</th><th style="text-align: center;background-color: #eee;">所属机构</th><th style="text-align: center;background-color: #eee;">会签意见</th><th style="text-align: center;background-color: #eee;">附件</th></tr><tbody id="jointlysignnodecode'+data.datas[i].NODECODE+'"></tbody></table></div></div>';
								$("#jointlysignopiniontable").append(html);
								for(j=0;j<opiniondata.datas.length;j++){
									var trStr = ''+
									  '	<tr>'+
									  '		<td>'+
									  		opiniondata.datas[j].username +
									  '		</td>'+
									  '		<td>'+
									  		opiniondata.datas[j].orgname + '（'+ opiniondata.datas[j].orgcode +'）' +
									  '		</td>'+
									  '		<td>'+
									  		(opiniondata.datas[j].opinion?opiniondata.datas[j].opinion:"")+
									  '</td>'+
									  '		<td>'+
									  '<span id="annex'+(opiniondata.datas[j].opinionid?opiniondata.datas[j].opinionid:"")+'"></span>'+
									  '		</td>'+
									  '	</tr>';	
									$("#jointlysignnodecode"+data.datas[i].NODECODE).append(trStr);
									if(opiniondata.datas[j].opinionid){
										$.ajax({ 
											url: basePath() + 'business/getaduitannex.do',
											data: {"opinionid": opiniondata.datas[j].opinionid},
											dataType: "json",
											async:false,
									        contentType: "application/json",
											success: function(annexdata){
												if(annexdata.result == 1){
													for(var k=0; k<annexdata.datas.length; k++){
														var html='<a target="_blank" href="/gahCMP/business/getannexidbyid.do?annexid='+annexdata.datas[k].annexid+'"><button type="button" class="btn btn-link">'+annexdata.datas[k].filename+'</button></a>';
											             $("#annex"+ opiniondata.datas[j].opinionid).append(html);  
													}
												}
									      	}
										});
									}
									
								}
							}
				      	}
					});
				}
			}
			
      	}
	});
}